/*************************************************************************
 * File Name:    Search_for_a_Range.cc
 * Author:       zero91
 * Mail:         jianzhang9102@gmail.com
 * Created Time: 2013/11/16 14:04:52
 * 
 * Description:  
 |------------------------------------------------------------------------
 | Problem: Search for a Range
 |
 | Given a sorted array of integers, find the starting and ending position of a given target value.
 |
 | Your algorithm's runtime complexity must be in the order of O(log n).
 |
 | If the target is not found in the array, return [-1, -1].
 |
 | For example,
 | Given [5, 7, 7, 8, 8, 10] and target value 8,
 | return [3, 4].
 |------------------------------------------------------------------------
 ************************************************************************/

#include <iostream>
#include <fstream>
#include <sstream>
#include <algorithm>
#include <vector>
#include <queue>
#include <stack>
#include <deque>
#include <map>
#include <set>
#include <functional>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <cctype>
#include <cmath>

using namespace std;

class Solution {
private:
    // return the index which value greater than or equal to val
    int lower_bound(int A[], int n, int val)
    {
        int left, right, mid;
        
        left = 0, right = n - 1;
        while (left < right) {
            mid = left + (right - left) / 2;
            if (A[mid] >= val) {
                right = mid;
            } else {
                left = mid + 1;
            }
        }
        return A[right] < val ? n : right;
    }
    
    // return the index which value greater than val
    int upper_bound(int A[], int n, int val)
    {
        int left, right, mid;
        
        left = 0, right = n - 1;
        while (left < right) {
            mid = left + (right - left) / 2;
            if (A[mid] > val) {
                right = mid;
            } else {
                left = mid + 1;
            }
        }
        return A[right] <= val ? n : right;
    }
    
public:
    vector<int> searchRange(int A[], int n, int target)
    {
        vector<int> ans;
        
        int left = lower_bound(A, n, target);
        int right = upper_bound(A, n, target);
        
        if (left == right) {
            ans.push_back(-1);
            ans.push_back(-1);
        } else {
            ans.push_back(left);
            ans.push_back(right - 1);
        }
        return ans;
    }
};

